package com.aivin.lib_login.icallback;

import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

/**
 * 瀑布流 的滑动到底的监控器
 */
public abstract class StaggeredGridLayoutManagerEndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {

    /**
     * 用来标记是否正在向上滑动
     */
    private boolean isSlidingUpward = false;
    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);

        StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
        if(manager==null){
            throw new RuntimeException("manager is null ....") ;
        }

        manager.invalidateSpanAssignments(); //防止第一行到顶部有空白区域

        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            int []  positions = manager.findLastVisibleItemPositions(null);
            int lastPos=0 ;
            for(int pos : positions){
                if(pos > lastPos){
                    lastPos = pos;
                }
            }
            int itemCount = manager.getItemCount();

            // 判断是否滑动到了最后一个item，并且是向上滑动
            if (lastPos == (itemCount - 1) && isSlidingUpward) {
                //加载更多
                onLoadMore();
            }
        }
    }
    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        // 大于0表示正在向上滑动，小于等于0表示停止或向下滑动
        isSlidingUpward = dy > 0;
    }
    /**
     * 加载更多回调
     */
    public abstract void onLoadMore();
}
